#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : gtmsAutoTestProject 
@File    : base_api.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/4/25 14:39 
@Describe: 接口请求基类
"""
import requests
from Config.yamlRead import interfaceName_cfg
from Comm.logUtils.logControl import LogHandler
from Comm.tools.toolsControl import ToolsHandler
from Comm.sqlUtils.sqliteControl import SqliteHelper
from FastApi.enum.Interface_enum.error_enum import ERROR_ENUM
from Comm.workWeiXinUtils.workWeiXinControl import send_workWeiXin_msg, api_error_log_insert


class BaseApi(object):
    """接口请求基类"""

    def __init__(self):
        self.logger = LogHandler().get_logger()
        self.sqlite = SqliteHelper('support.db')
        self.url = ''
        self.type = ''

    def http_requests(self, url, payload):
        post_url = self.url + url  # 拼接请求url
        response = requests.request("POST", url=post_url, headers=self.get_headers(), data=payload)  # 请求接口
        response_time = response.elapsed.total_seconds()  # 接口响应时间
        response_code = ToolsHandler.get_json_result(response, '$.code')  # 接口响应状态码
        TraceId = ToolsHandler.get_json_valus(response.headers, key='X-B3-TraceId')  # 日志ID
        try:
            port_name = interfaceName_cfg['{}'.format(url)]  # 获取yaml文件中接口映射的中文名
        except KeyError as e:
            self.logger.warning("配置文件未获取到该接口的中文名称。错误的键名:{0};错误信息:{1};".format(url, e))
            port_name = url  # 没有找到就用传值名称
        # 输出接口请求通用日志
        self.logger.info('*' * 20 + '接口请求开始' + '*' * 20)
        self.logger.info('接口名称:{}'.format(port_name))
        self.logger.info('请求路径:{}'.format(post_url))
        self.logger.info('请求参数:{}'.format(payload))
        self.logger.info('接口响应信息:{}'.format(response.text))
        self.logger.info('TraceId:{}'.format(TraceId))
        # 输出接口请求成功日志
        if response_code == 200:
            self.logger.info('接口响应时间:{}秒'.format(response_time))
            self.logger.info('接口请求成功！')
            self.logger.info('*' * 20 + '接口请求结束' + '*' * 20)
            return response
        # 输出接口请求失败日志
        else:
            error_message = ToolsHandler.get_json_result(response, '$..message')  # 错误信息
            self.logger.error('错误信息:{}'.format(error_message))
            self.logger.error('接口请求失败!')
            self.logger.info('*' * 20 + '接口请求结束' + '*' * 20)
            send_workWeiXin_msg(post_url, port_name, payload, error_message, TraceId)  # 企业微信推送错误消息
            api_error_log_insert(post_url, self.type, port_name, payload, response_time, response_code, response.text, TraceId)
            result_info = {"code": response_code, "message": ERROR_ENUM.SYSTEM_ERROR.value[1].format(payload, error_message)}
            return result_info

    def get_headers(self) -> None:
        ...
